package cn.enjoy.boot.service.impl;

import cn.enjoy.boot.entity.Fake;
import cn.enjoy.boot.mapper.FakeMapper;
import cn.enjoy.boot.service.DXCService;
import io.jsonwebtoken.lang.Collections;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author K
 * @date 2021-11-09 21:42
 */
@Service
public class DXCServiceImpl implements DXCService {
    @Resource
    private FakeMapper fakeMapper;
    private final ExecutorService executorService = Executors.newFixedThreadPool(20);
    private final AtomicLong sum = new AtomicLong(0);


    @SneakyThrows
    public void callSum() {
//        Integer count = fakeMapper.selectCount(Wrappers.emptyWrapper());
        int pageSize = 200;
        long lastNo = 0L;
        long maxNo = 1000;
        Future<?> future = null;
        long start = System.currentTimeMillis();
        while (lastNo < maxNo) {
            List<Fake> fakeList = fakeMapper.selectFakeList(lastNo, pageSize);
            if (Collections.isEmpty(fakeList)) {
                break;
            }
            Fake lastFake = fakeList.get(fakeList.size() - 1);
            lastNo = lastFake.getId();
            future = executorService.submit(() -> {
                sum.addAndGet(add(fakeList));
            });
        }

        // 不能使用executorService.shutdown(); 会将这个线程池的所有线程都杀掉，就没有线程继续使用，造成后面的请求过来就会报错
//        executorService.shutdown();
//        while (true) {
//            if (executorService.isTerminated()) {
//                System.out.println("任务结束");
//                break;
//            } else {
//                Thread.sleep(2000);
//            }
//        }

        while (true) {
            if (future.isDone()) {
                break;
            } else {
                Thread.sleep(2000);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("Result：" + sum.get() + "\n用时：" + (end - start) / 1000 + "s");
        sum.set(0);
    }

    public Long add(List<Fake> fakeList) {
        LongSummaryStatistics statistics = fakeList.stream().mapToLong(Fake::getAmount).summaryStatistics();
        return statistics.getSum();
    }

}
